cmake_minimum_required(VERSION 3.10)

add_library(mx_aws_iot_proto)

SET(MX_AWS_IOT_PROTOBUF_OUTPUT_DIR "${CMAKE_BINARY_DIR}/mx_aws_iot-protobuf-output")
# 创建命名空间目录
file(MAKE_DIRECTORY ${MX_AWS_IOT_PROTOBUF_OUTPUT_DIR}/mx_aws_iot)

set(MX_AWS_IOT_PROTO_FLAGS)
LIST(APPEND MX_AWS_IOT_PROTO_FLAGS "-I${CMAKE_CURRENT_LIST_DIR}")
# 修改输出路径，包含命名空间目录
LIST(APPEND MX_AWS_IOT_PROTO_FLAGS "--cpp_out=${MX_AWS_IOT_PROTOBUF_OUTPUT_DIR}/mx_aws_iot")
file(GLOB_RECURSE MX_AWS_IOT_PROTOS ${CMAKE_CURRENT_LIST_DIR}/*.proto)

set(MX_AWS_IOT_MESSAGE_SRC)
set(MX_AWS_IOT_MESSAGE_HDRS)

set(MX_AWS_IOT_PROTOC_EXECUTABLE ${PROTOBUF_PROTOC_EXECUTABLE})

foreach(msg ${MX_AWS_IOT_PROTOS})
    get_filename_component(FIL_WE ${msg} NAME_WE)
    set(OUTPUT_SRC "${MX_AWS_IOT_PROTOBUF_OUTPUT_DIR}/mx_aws_iot/${FIL_WE}.pb.cc")
    set(OUTPUT_HDR "${MX_AWS_IOT_PROTOBUF_OUTPUT_DIR}/mx_aws_iot/${FIL_WE}.pb.h")

    list(APPEND MX_AWS_IOT_MESSAGE_SRC ${OUTPUT_SRC})
    list(APPEND MX_AWS_IOT_MESSAGE_HDRS ${OUTPUT_HDR})

    add_custom_command(
        OUTPUT ${OUTPUT_SRC} ${OUTPUT_HDR}
        COMMAND ${MX_AWS_IOT_PROTOC_EXECUTABLE} ${MX_AWS_IOT_PROTO_FLAGS} ${msg}
        DEPENDS ${msg}
        COMMENT "Generating protobuf files for ${msg}"
        VERBATIM
    )
endforeach()

target_sources(mx_aws_iot_proto PRIVATE ${MX_AWS_IOT_MESSAGE_SRC})

# 修改包含目录，指向根目录
target_include_directories(mx_aws_iot_proto PUBLIC ${MX_AWS_IOT_PROTOBUF_OUTPUT_DIR})
target_link_libraries(mx_aws_iot_proto PUBLIC protobuf::libprotobuf)
